#include "timer.h"
#include "stm32f1xx_hal.h"

void timer_init(void)
{
	__HAL_RCC_GPIOA_CLK_ENABLE();
	__HAL_RCC_GPIOB_CLK_ENABLE();
	__HAL_RCC_AFIO_CLK_ENABLE();
	__HAL_RCC_TIM2_CLK_ENABLE();	
	__HAL_RCC_TIM3_CLK_ENABLE();	
	
	GPIOA->CRL &= 0x00FF0000;
	GPIOA->CRL |= 0xBB00BBBB;
	
	GPIOB->CRL &= 0xFFFFFF00;
	GPIOB->CRL |= 0x000000BB;
	
	/* timer2 init */
	TIM2->PSC = 71;
	TIM2->ARR = 20000;
	
	TIM2->CCMR1  = 0;
	TIM2->CCMR2  = 0;
	TIM2->CCMR1 |= 0x60;//CH1 PWM1
	TIM2->CCMR1 |= 0x60<<8;//CH2 PWM1
	TIM2->CCMR2 |= 0x60;//CH3 PWM1
	TIM2->CCMR2 |= 0x60<<8;//CH4 PWM1
	
	TIM2->CCER  |= 0x01<<0;//enable ch1
	TIM2->CCER  |= 0x01<<4;//enable ch2	
	TIM2->CCER  |= 0x01<<8;//enable ch3
	TIM2->CCER  |= 0x01<<12;//enable ch4	
	
	TIM2->CCR1 = 1500;
	TIM2->CCR2 = 1500;
	TIM2->CCR3 = 1500;
	TIM2->CCR4 = 1500;
	
	/* timer3 init */
	TIM3->PSC = 71;
	TIM3->ARR = 20000;
	
	TIM3->CCMR1  = 0;
	TIM3->CCMR2  = 0;
	TIM3->CCMR1 |= 0x60;//CH1 PWM1
	TIM3->CCMR1 |= 0x60<<8;//CH2 PWM1
	TIM3->CCMR2 |= 0x60;//CH3 PWM1
	TIM3->CCMR2 |= 0x60<<8;//CH4 PWM1
	
	TIM3->CCER  |= 0x01<<0;//enable ch1
	TIM3->CCER  |= 0x01<<4;//enable ch2	
	TIM3->CCER  |= 0x01<<8;//enable ch3
	TIM3->CCER  |= 0x01<<12;//enable ch4	
	
	TIM3->CCR1 = 1500;
	TIM3->CCR2 = 1500;
	TIM3->CCR3 = 1500;
	TIM3->CCR4 = 1500;
}

void timer_start(void)
{
	TIM2->CR1 |= 0x01;
	TIM3->CR1 |= 0x01;
}

void pwm_output(int ch, int us)
{
	if(us<1000) {
		us =1000;
	}
	if(us > 2000) {
		us = 2000;
	}
	switch(ch)
	{
		case 0:
			TIM2->CCR1 = (uint16_t)us;
			break;
		case 1:
			TIM2->CCR2 = (uint16_t)us;
			break;
		case 2:
			TIM2->CCR3 = (uint16_t)us;
			break;
		case 3:
			TIM2->CCR4 = (uint16_t)us;
			break;
		case 4:
			TIM3->CCR1 = (uint16_t)us;
			break;
		case 5:
			TIM3->CCR2 = (uint16_t)us;
			break;
		case 6:
			TIM3->CCR3 = (uint16_t)us;
			break;
		case 7:
			TIM3->CCR4 = (uint16_t)us;
			break;
	}	
}
